<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span
          style="
            display: inline-block;
            width: calc(100% - 51px);
            padding-right: 10px;
            text-align: right;
          "
        >
          <a-button
            @click="toggleScreen"
            icon="appstore"
            style="height: 20px; width: 20px; border: 0px"
          ></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="用户账号"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入用户账号"
            :maxLength="20"
            :disabled="title == '详情' ? true : false"
            v-decorator.trim="[
              'loginName',
              {
                rules: validatorRules.username.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(/[^\w\/]/gi, '');
                },
              },
            ]"
            :readOnly="!!model.id || title == '编辑'"
          />
        </a-form-item>

        <template v-if="!model.userId">
          <a-form-item
            label="登录密码"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input
              type="password"
              placeholder="请输入登录密码"
              v-decorator="['password', validatorRules.password]"
              :maxLength="20"
              oninput="value=value.replace(/[, ]/g,'')"
              onkeyup="value=value.replace(/[, ]/g,'') "
            />
          </a-form-item>

          <a-form-item
            label="确认密码"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-input
              type="password"
              @blur="handleConfirmBlur"
              placeholder="请再次输入新密码"
              :maxLength="20"
              v-decorator="['confirmpassword', validatorRules.confirmpassword]"
              oninput="value=value.replace(/[, ]/g,'')"
              onkeyup="value=value.replace(/[, ]/g,'') "
            />
          </a-form-item>
        </template>
        <a-form-item
          label="角色分配"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="!roleDisabled"
        >
          <a-select
          :onFocus="handleValue()"
            mode="multiple"
            :disabled="title == '详情' ? true : false"
            style="width: 100%"
            placeholder="请选择用户角色"
            optionFilterProp="children"
            :getPopupContainer="(target) => target.parentNode"
            v-decorator.trim="['roleIds', validatorRules.roleIds]"
          >
            <a-select-option
              v-for="(role, roleindex) in roleList"
              :key="roleindex.toString()"
              :value="role.roleId"
            >
              {{ role.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="用户姓名"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入用户姓名"
            v-decorator.trim="['realName', validatorRules.realName]"
            maxLength="20"
            :disabled="title == '详情' ? true : false"
          />
          <!--  validatorRules.realname 验证 -->
        </a-form-item>
        <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            v-decorator="['sex', {}]"
            placeholder="请选择性别"
            :getPopupContainer="(target) => target.parentNode"
            :disabled="title == '详情' ? true : false"
          >
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="2">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="手机号码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <!--  原先禁用判断      :disabled="isDisabledAuth('user:form:mobile')"    -->
          <a-input
            placeholder="请输入手机号码"
            :disabled="title == '详情' ? true : false"
            v-decorator="['mobile', validatorRules.phone]"
            maxLength="11"
          />
          <!--  validatorRules.phone 验证    -->
          <!-- :readOnly="title == '编辑'" -->
        </a-form-item>
        <!--				<a-form-item label="昵称" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
        <!--					<a-input placeholder="请输入昵称" v-decorator.trim="['nickName']" />-->
        <!--				</a-form-item>-->

        <!--部门分配-->
        <!--				<a-form-item label="部门分配" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="!departDisabled">-->
        <!--					<a-tree-select style="width:100%" :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }" :replaceFields="{children:'children', title:'deptName'}"-->
        <!--					:treeData="treeData" placeholder="请选择部门" :disabled="disableSubmit" :defaultExpandAll="true" v-decorator.trim="[ 'deptId', validatorRules.deptId]">-->
        <!--					</a-tree-select>-->
        <!--				</a-form-item>-->
        <!--				<a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
        <!--					<a-date-picker style="width: 100%" placeholder="请选择生日" v-decorator="['birthday']" format="YYYY-MM-DD"-->
        <!--					:getCalendarContainer="node => node.parentNode" :disabled="title == '编辑'"/>-->
        <!--				</a-form-item>-->

        <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            :disabled="title == '详情' ? true : false"
            placeholder="请输入邮箱"
            v-decorator="['email', validatorRules.email]"
            maxLength="30"
          />
        </a-form-item>
      </a-form>
    </a-spin>

    <!-- <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
      >
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading"
        >提交</a-button
      >
    </div> -->

    <!--  编辑与详情 合为一个按钮 -->
    <div class="drawer-bootom-button">
      <a-button
        @click="handleEdit"
        type="primary"
        :loading="confirmLoading"
        v-if="!disabledEditValue && disabledAddValue"
        >编辑</a-button
      >
      <a-button
        @click="handleSubmit"
        type="primary"
        :loading="confirmLoading"
        v-if="disabledEditValue && !disabledAddValue"
        >提交</a-button
      >
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
        v-if="disabledEditValue"
      >
        <a-button style="margin-left: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button
        style="margin-left: 0.8rem"
        v-if="!disabledEditValue"
        @click="handleCancel"
        >取消</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import pick from "lodash.pick";
import { getAction } from "@/api/manage";
import moment from "moment";
import { addUser, editUser, queryall, queryIdTree } from "@/api/api";
import { disabledAuthFilter } from "@/utils/authFilter";
import JImageUpload from "../../../components/jeecg/JImageUpload";

export default {
  name: "UserModal",
  components: {
    JImageUpload,
  },
  data() {
    return {
      departDisabled: false, //是否是我的部门调用该页面
      roleDisabled: false, //是否是角色维护调用该页面
      modalWidth: 800,
      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      userId: "", //保存用户id
      // disableSubmit: false,
      userDepartModel: {
        userId: "",
        departIdList: [],
      }, // 保存SysUserDepart的用户部门中间表数据需要的对象
      dateFormat: "YYYY-MM-DD",
      validatorRules: {
        username: {
          rules: [
            {
              required: true,
              message: "请输入用户账号!",
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              pattern: /^.{6,20}$/,
              message: "登录密码长度必须介于6位和20位之间!",
            },
            {
              validator: this.validateToNextPassword,
            },
          ],
        },
        // password: {
        //   rules: [
        //     {
        //       required: true,
        //       pattern:
        //         /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
        //       message: "密码由8位数字、大小写字母和特殊符号组成!",
        //     },
        //     {
        //       validator: this.validateToNextPassword,
        //     },
        //   ],
        // },
        confirmpassword: {
          rules: [
            {
              required: true,
              // pattern: /^.{6,20}$/,
              message: "请再次输入新密码!",
            },
            {
              validator: this.compareToFirstPassword,
            },
          ],
        },
        realName: {
          rules: [
            {
              required: true,
              message: "请输入用户名称!",
            },
          ],
        },
        phone: {
          rules: [
            {
              // required: true,
              // validator: this.validatePhone,
            },
          ],
        },
        email: {
          rules: [
            {
              validator: this.validateEmail,
            },
          ],
        },
        roles: {},
        //  sex:{initialValue:((!this.model.sex)?"": (this.model.sex+""))}
        deptId: {
          rules: [
            {
              // required: true,
              message: "请选择部门",
            },
          ],
        },
        roleIds: {
          rules: [
            {
              required: true,
              message: "请选择用户角色!",
            },
          ],
        },
      },
      title: "操作",
      visible: false,
      model: {},
      roleList: [],
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      uploadLoading: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      picUrl: "",
      url: {
        fileUpload: window._CONFIG["domianURL"] + "/sys/common/upload",
        userId: "/sys/user/generateUserId", // 引入生成添加用户情况下的url
      },
      currentTenant: [],
      treeData: [],
    };
  },
  created() {
    this.initTreeData();
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    },
  },

  methods: {
    handleValue() {
      console.log('ant-select-search__fieldant-select-search__fieldant-select-search__field')
      const auctionTimesCode = document.querySelector(
        ".ant-select-search__field"
      );
      auctionTimesCode && auctionTimesCode.setAttribute("readonly", "true");
    },
    // 编辑
    handleEdit() {
      this.title = "编辑";
      this.disabledEditValue = true;
      this.disabledAddValue = false;
    },
    isDisabledAuth(code) {
      return disabledAuthFilter(code);
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    initialRoleList() {
      let postData = {
        current: 1,
        deptCode: "",
        roleName: "",
        size: 10,
      };
      queryall(postData).then((res) => {
        if (res.code == "00000") {
          this.roleList = res.data;
        } else {
          console.log(res);
        }
      });
    },
    refresh() {
      this.userId = "";
      this.departId = [];
      this.currentTenant = [];
    },
    add() {
      this.picUrl = "";
      this.refresh();
      this.edit({});
    },
    edit(record) {
      console.log(record);
      if (record.userId) {
        let that = this;
        getAction("/sys/user/info/" + record.userId).then((res) => {
          if (res.code == "00000") {
            this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
            that.initialRoleList();
            that.form.resetFields();
            that.userId = res.data.userId;
            that.visible = true;
            that.model = Object.assign({}, res.data);
            if (that.model.birthday != null) {
              that.model.birthday = moment(res.data.birthday, "YYYY-MM-DD");
            }
            console.log(that.model);
            that.$nextTick(() => {
              that.form.setFieldsValue(
                pick(
                  that.model,
                  "loginName",
                  "sex",
                  "birthday",
                  "realName",
                  "nickName",
                  "email",
                  "mobile",
                  "deptId",
                  "roleIds"
                )
              );
            });
          } else {
            that.$message.warning("查询失败");
          }
        });
      } else {
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.initialRoleList();
        this.form.resetFields();
        this.userId = record.userId;
        this.visible = true;
        this.model = Object.assign({}, record);
        this.$nextTick(() => {
          this.form.setFieldsValue(
            pick(
              this.model,
              "loginName",
              "sex",
              "birthday",
              "realName",
              "nickName",
              "email",
              "mobile",
              "deptId",
              "roleIds"
            )
          );
        });
      }
    },
    initTreeData() {
      let that = this;
      queryIdTree().then((res) => {
        if (res.code == "00000") {
          that.treeData = res.data;
        }
      });
    },

    close() {
      this.$emit("close");
      this.visible = false;
      // this.disableSubmit = false;
      this.userDepartModel = {
        userId: "",
        departIdList: [],
      };
    },
    moment,
    handleSubmit() {
      const that = this;

      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          if (!values.birthday) {
            values.birthday = "";
          } else {
            values.birthday = values.birthday.format(this.dateFormat);
          }
          let formData = Object.assign(this.model, values);
          formData.selecteddeparts =
            this.userDepartModel.departIdList.length > 0
              ? this.userDepartModel.departIdList.join(",")
              : "";
          delete formData.confirmpassword;
          // that.addDepartsToUser(that,formData); // 调用根据当前用户添加部门信息的方法
          let obj;
          if (!this.model.userId) {
            formData.userId = this.userId;
            obj = addUser(formData);
          } else {
            obj = editUser(formData);
          }
          console.log(formData);
          obj
            .then((res) => {
              if (res.code == "00000") {
                that.$message.success("操作成功");
                that.$emit("ok");
              } else {
                that.$message.warning("操作失败" + res.msg);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.userDepartModel.departIdList = {
                userId: "",
                departIdList: [],
              };
              that.close();
            });
        }
      });
    },
    handleCancel() {
      this.close();
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      const confirmpassword = form.getFieldValue("confirmpassword");

      if (value && confirmpassword && value !== confirmpassword) {
        callback("两次输入的密码不一样！");
      }
      if (value && this.confirmDirty) {
        form.validateFields(["confirm"], {
          force: true,
        });
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue("password")) {
        callback("两次输入的密码不一样！");
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback("请输入手机号码!");
      } else {
        //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
          //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
          callback();
        } else {
          callback("请输入正确格式的手机号码!");
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (
          //正则验证
          new RegExp(
            // /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            // /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            /^([a-zA-Z]|[0-9])(\w|)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
          ).test(value)
        ) {
          callback();
        } else {
          callback("请输入正确格式的邮箱!");
        }
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    // handleChange(info) {
    // 	this.picUrl = "";
    // 	if (info.file.status === 'uploading') {
    // 		this.uploadLoading = true;
    // 		return
    // 	}
    // 	if (info.file.status === 'done') {
    // 		var response = info.file.response;
    // 		this.uploadLoading = false;
    // 		console.log(response);
    // 		if (response.success) {
    // 			this.model.avatar = response.message;
    // 			this.picUrl = "Has no pic url yet";
    // 		} else {
    // 			this.$message.warning(response.message);
    // 		}
    // 	}
    // },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
  },
};
</script>

<style scoped lang="less">
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

/deep/.ant-select-selection__rendered{
  cursor: pointer;
}
</style>
